import smtplib
import json
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os,time,math
from tty import CC

#返回文件最后一行函数
def get_last_two_line(inputfile) :
    dat_file = open(inputfile, 'r')
    lines = dat_file.readlines()
    last_two_line = []
    if lines :
        last_two_line = lines[-2].strip()

    dat_file.close()
    return last_two_line


with open("./testPro/testPro/conf/config.json",'r') as load_f1:
    config = json.load(load_f1)

smtpserver = 'smtp.163.com'
smtpport = 465
sender = 'easyst2021@163.com'
sender_pwd = 'LCYWTURBOXNOLGME'

rece = config["MailRecivers"]
mail_username = 'easyst2021'

# 创建一个带附件的邮件实例
message=MIMEMultipart()
# 编辑邮件的内容

# 往邮件容器中添加内容。这是邮件的主体
mail_title = 'TAB Crawl ' + time.asctime( time.localtime(time.time()))
content = r"This week is WW"+str(math.ceil(time.localtime()[7]/7+1))\
    +'\n'+'last running time '+ get_last_two_line('./history.txt')

mail_inside = MIMEText(content,'plain','utf-8')
# 邮件的其他属性
message['From'] = sender
message['To'] = ','.join(rece)
message['Subject'] = Header(mail_title,'utf-8')
message.attach(mail_inside)

filename = "WW"+str(math.ceil(time.localtime()[7]/7+1))+'.zip'
#构造附件txt附件1
attr1=MIMEText(open(r'./result.zip','rb').read(),'base64','utf-8')
attr1["content_Type"]='application/octet-stream'
attr1["Content-Disposition"] = 'attachment; filename='+filename # 表示这是附件，名字是啥
message.attach(attr1)
 
 
 
# # 构造图片附件2
# att2 = MIMEText(open(r'D:\flower.jpg','rb').read(), 'base64', 'utf-8')
# att2["Content-Type"] = 'application/octet-stream'
# att2["Content-Disposition"] = 'attachment; filename="flower.jpg"'
# message.attach(att2)
 
# #构造html附件
# att3 = MIMEText(open('report_test.html', 'rb').read(), 'base64', 'utf-8')
# att3["Content-Type"] = 'application/octet-stream'
# att3["Content-Disposition"] = 'attachment; filename="report_test.html"'
# message.attach(att3)
 
 
smtpobj = smtplib.SMTP_SSL(smtpserver, port=smtpport)
smtpobj.login(sender, sender_pwd)
smtpobj.sendmail(sender,rece,message.as_string())
print ('邮件发送成功')
smtpobj.quit()